#coding=utf-8
from flask import Flask,render_template,Response
import cv2
import time
import io
import fcntl

resultOutputFile = '/run/test.jpg'
app = Flask(__name__)

def putFrame(frame):
    f = open(resultOutputFile, 'wb')
    fcntl.flock(f,fcntl.LOCK_EX)
    cv2.imwrite(resultOutputFile,frame)
    fcntl.flock(f,fcntl.LOCK_UN)
    f.close()

@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')


def gen():
    """Video streaming generator function."""
    frame1 = None
    while True:
        try:
            time.sleep(0.05)
            fd = open(resultOutputFile, 'rb')
            fcntl.flock(fd,fcntl.LOCK_EX)
            frame1 = fd.read()
            fcntl.flock(fd,fcntl.LOCK_UN)
            fd.close()
            yield (b'--frame\r\n'
                    b'Content-Type: image/jpeg\r\n\r\n' + frame1 + b'\r\n')
        except Exception,e:
            print Exception,e
            pass


@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=5000,threaded=False)